<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\UserToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        // 记录请求信息
        Log::info('收到获取订单列表请求', [
            'headers' => $request->header()
        ]);

        try {
            // 验证token
            $token = str_replace('Bearer ', '', $request->header('Authorization'));
            
            if (empty($token)) {
                Log::warning('获取订单列表失败：未提供token');
                return response()->json([
                    'message' => '请先登录'
                ], 401);
            }

            // 检查token是否存在且在有效期内
            $userToken = UserToken::where('token', $token)
                    ->where('expired_at', '>', Carbon::now())
                    ->first();

            if (!$userToken) {
                Log::warning('获取订单列表失败：token无效或已过期', [
                    'token' => $token
                ]);
                return response()->json([
                    'message' => 'token已过期，请重新登录'
                ], 401);
            }

            // 获取用户的订单列表
            $orders = Order::with([
                'product:id,name,price',  // 只选择需要的商品字段
                'shippingAddress:id,receiver_name,receiver_phone,receiver_address'  // 只选择需要的地址字段
            ])
            ->where('wechat_user_id', $userToken->wechat_user_id)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($order) {
                try {
                    return [
                        'order_number' => $order->order_number,
                        'status' => $order->status,
                        'status_text' => $this->getStatusText($order->status),
                        'product_name' => $order->product->name ?? '商品已删除',
                        'product_price' => $order->product->price ?? 0.00,
                        'created_at' => $order->created_at->format('Y-m-d H:i:s'),
                        'shipping_info' => $order->shippingAddress ? [
                            'receiver_name' => $order->shippingAddress->receiver_name,
                            'receiver_phone' => $order->shippingAddress->receiver_phone,
                            'receiver_address' => $order->shippingAddress->receiver_address
                        ] : null,
                        'logistics_info' => $this->getLogisticsInfo($order)
                    ];
                } catch (\Exception $e) {
                    Log::error('订单数据处理异常', [
                        'order_id' => $order->id,
                        'error' => $e->getMessage()
                    ]);
                    return null;
                }
            })
            ->filter(); // 移除可能的 null 值

            // 改进日志记录
            Log::info('获取订单列表成功', ['orders' => $orders]);

            return response()->json([
                'success' => true,
                'data' => $orders
            ]);

        } catch (\Exception $e) {
            Log::error('获取订单列表过程发生异常', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => '服务器错误，请稍后重试'
            ], 500);
        }
    }

    // 获取订单状态文本
    private function getStatusText($status)
    {
        $statusMap = [
            0 => '待发货',
            1 => '已发货',
            2 => '已完成',
            3 => '已取消'
        ];

        return $statusMap[$status] ?? '未知状态';
    }

    // 获取物流信息
    private function getLogisticsInfo($order)
    {
        try {
            if (!$order->logistics_company || !$order->tracking_number) {
                return null;
            }

            // 检查 shipped_at 是否为 Carbon 实例
            $shippedAt = null;
            if ($order->shipped_at) {
                if ($order->shipped_at instanceof \Carbon\Carbon) {
                    $shippedAt = $order->shipped_at->format('Y-m-d H:i:s');
                } else {
                    // 如果不是 Carbon 实例，尝试转换
                    $shippedAt = \Carbon\Carbon::parse($order->shipped_at)->format('Y-m-d H:i:s');
                }
            }

            return [
                'company' => $order->logistics_company,
                'number' => $order->tracking_number,
                'shipped_at' => $shippedAt
            ];
        } catch (\Exception $e) {
            Log::error('处理物流信息时发生错误', [
                'order_id' => $order->id,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }
} 